<template>
  <div class="appointments">
    <el-card class="appointment-form">
      <template #header>
        <div class="page-header">
          <h2>陪诊预约</h2>
          <el-button type="primary" @click="showHistory">预约记录</el-button>
        </div>
      </template>

      <el-steps :active="activeStep" finish-status="success" class="appointment-steps">
        <el-step title="预约信息" description="填写就诊信息"></el-step>
        <el-step title="选择陪护师" description="挑选合适的陪护师"></el-step>
        <el-step title="确认支付" description="确认订单并支付"></el-step>
      </el-steps>

      <!-- 步骤1：预约信息 -->
      <div v-if="activeStep === 0" class="step-content">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="就诊人姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入就诊人姓名"></el-input>
              </el-form-item>
            </el-col>
            <!-- 在步骤1的el-form中增加以下字段 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" placeholder="请选择性别">
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input-number
                    v-model="form.age"
                    :min="1"
                    :max="120"
                    controls-position="right">
                  </el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="就诊医院" prop="hospital">
                <el-select v-model="form.hospital" placeholder="请选择就诊医院">
                  <el-option
                    v-for="hospital in hospitals"
                    :key="hospital.id"
                    :label="hospital.name"
                    :value="hospital.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就诊科室" prop="department">
                <el-select v-model="form.department" placeholder="请选择就诊科室">
                  <el-option
                    v-for="dept in departments"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约时间" prop="appointmentTime">
                <el-date-picker
                  v-model="form.appointmentTime"
                  type="datetime"
                  placeholder="选择预约时间"
                  :disabled-date="disabledDate"
                  :disabled-hours="disabledHours">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务时长" prop="duration">
                <el-input-number 
                  v-model="form.duration" 
                  :min="1" 
                  :max="8"
                  @change="calculateTotal">
                </el-input-number>
                <span class="unit">小时</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注信息" prop="remarks">
            <el-input
              type="textarea"
              v-model="form.remarks"
              :rows="3"
              placeholder="请输入其他需要说明的信息">
            </el-input>
          </el-form-item>
        </el-form>

      </div>

      <!-- 步骤2：选择陪护师 -->
      <div v-if="activeStep === 1" class="step-content">
        <!-- 筛选条件 -->
        <el-form :inline="true" :model="filterForm" @submit.prevent="fetchEscortsByFilter">
          <el-form-item label="价格区间">
            <el-select v-model="filterForm.money" placeholder="请选择价格区间">
              <el-option label="50-100/小时" value="50-100"></el-option>
              <el-option label="100-150/小时" value="100-150"></el-option>
              <el-option label="150-200/小时" value="150-200"></el-option>
              <el-option label="200-250/小时" value="200-250"></el-option>
              <el-option label="250-300/小时" value="250-300"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="filterForm.gender" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄区间">
            <el-select v-model="filterForm.age" placeholder="请选择年龄区间">
              <el-option label="18-25" value="18-25"></el-option>
              <el-option label="25-35" value="25-35"></el-option>
              <el-option label="35-45" value="35-45"></el-option>
              <el-option label="45-55" value="45-55"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地区">
            <el-select v-model="filterForm.address" placeholder="请选择地区">
              <el-option label="金水区" value="金水区"></el-option>
              <el-option label="惠济区" value="惠济区"></el-option>
              <el-option label="中原区" value="中原区"></el-option>
              <el-option label="高新区" value="高新区"></el-option>
              <el-option label="二七区" value="二七区"></el-option>
              <el-option label="郑东新区" value="郑东新区"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="从业年限">
            <el-select v-model="filterForm.serviceyears" placeholder="请选择从业年限">
              <el-option label="小于2年" value="小于2年"></el-option>
              <el-option label="2-5年" value="2-5年"></el-option>
              <el-option label="5-10年" value="5-10年"></el-option>
              <el-option label="10年以上" value="10年以上"></el-option>
            </el-select>
          </el-form-item>
          <!-- 在筛选表单下方添加 -->
          <div class="filter-tags">
            <el-tag
              v-for="(value, key) in activeFilters"
              :key="key"
              closable
              @close="removeFilter(key)"
            >
              {{ filterLabels[key] }}: {{ value }}
            </el-tag>
          </div>
          <el-button type="primary" @click="fetchEscortsByFilter">筛选</el-button>
          <el-button @click="fetchAllEscorts">显示所有</el-button>
        </el-form>

        <!-- 新增根据 caregiverid 查询陪诊师信息 -->
        <el-form :inline="true" :model="caregiverQueryForm" @submit.prevent="fetchCaregiverById">
          <!-- 修改ID查询表单绑定 -->
          <el-form-item label="陪诊师ID">
            <el-input
              v-model="caregiverQueryForm.caregiverid"
              placeholder="输入陪诊师ID"
              @keyup.enter="fetchCaregiverById"
            ></el-input>
          </el-form-item>
          <el-button type="primary" @click="fetchCaregiverById">查询</el-button>
        </el-form>

            <el-row :gutter="20">
              <el-col :span="6" v-for="escort in escorts" :key="escort.id">
                <el-card
                  class="escort-card"
                  :class="{ selected: selectedEscort?.id === escort.id }"
                  @click.prevent="selectEscort(escort)"
                >
              <div class="escort-avatar">
                <el-avatar :size="100" :src="escort.avatar"></el-avatar>
                <div class="escort-status" :class="{ available: escort.is_available }">
                  {{ escort.is_available ? '可预约' : '已约满' }}
                </div>
              </div>
              <div class="escort-info">
                <h3>{{ escort.name }}</h3>
                <p class="escort-title">{{ escort.gender }} | {{ escort.age }}岁 | {{ escort.experience }}年经验</p>
                <p class="escort-intro">{{ escort.introduction }}</p>
                <div class="escort-rating">
                  <el-rate v-model="escort.rating" disabled></el-rate>
                  <span class="rating-text">{{ escort.rating }}分</span>
                </div>
                <div class="escort-price">
                  <span class="price">¥{{ escort.price }}</span>/小时
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <div class="publish-to-hall">
          <el-card class="publish-card" @click="publishToHall">
            <div class="publish-content">
              <el-icon :size="50"><Promotion /></el-icon>
              <h3>发布到接单大厅</h3>
              <p>让更多陪护师看到您的需求</p>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 步骤3：确认支付 -->
      <div v-if="activeStep === 2" class="step-content">
        <div class="order-summary">
          <h3>订单信息</h3>
          <div class="order-info-table">
            <el-table :data="[orderInfo]" border style="width: 100%">
              <el-table-column prop="escort" label="陪护师" width="120">
                    <!-- 将默认插槽移到 <el-table-column> 内部 -->
                    <template #default="scope">
                      {{ scope.row.escort || '待选择' }}
                    </template>
              </el-table-column>
              <el-table-column prop="name" label="就诊人" width="120"></el-table-column>
              <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
              <el-table-column prop="hospital" label="就诊医院"></el-table-column>
              <el-table-column prop="department" label="就诊科室" width="120"></el-table-column>
              <el-table-column prop="appointmentTime" label="预约时间" width="180"></el-table-column>
              <el-table-column prop="duration" label="服务时长" width="100"></el-table-column>
              <el-table-column prop="totalPrice" label="总价" width="120"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <div class="step-actions">
        <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
        <el-button
          type="primary"
          v-if="activeStep < 2"
          @click="nextStep">
          下一步
        </el-button>
        <el-button
          type="primary"
          v-if="activeStep === 2"
          @click="submitOrder">
          确认支付
        </el-button>
      </div>
    </el-card>

    <!-- 预约记录对话框 -->
    <el-dialog
      v-model="showHistoryDialog"
      title="预约记录"
      width="70%">
      <el-table :data="appointmentHistory" style="width: 100%">
        <el-table-column prop="order_no" label="订单号" width="180"></el-table-column>
        <el-table-column prop="patient_name" label="就诊人" width="120"></el-table-column>
        <el-table-column prop="escort_name" label="陪护师" width="120"></el-table-column>
        <el-table-column prop="hospital" label="医院"></el-table-column>
        <el-table-column prop="appointment_time" label="预约时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import {ip} from '../router/ip.js'

import { getEscortList } from '@/api/escort'
import { getHospitalList } from '@/api/hospital'
import {
  createAppointment,
  getPaymentQRCode,
  checkPaymentStatus,
  getAppointmentList
} from '@/api/appointment'
import { formatDateTime } from '@/utils/date'

// 步骤索引
const activeStep = ref(0)
// 陪护师列表
const escorts = ref([])
// 选中的陪护师
const selectedEscort = ref(null)
// 支付方式
const paymentMethod = ref('wechat')
// 表单引用
const formRef = ref(null)

// 医院列表（固定数据）
const hospitals = ref([
  { id: 1, name: '北京协和医院' },
  { id: 2, name: '北京大学第一医院' },
])

// 科室列表（固定数据）
const departments = ref([
  { id: 1, name: '内科' },
  { id: 2, name: '外科' },
  { id: 3, name: '妇产科' },
  { id: 4, name: '儿科' },
  { id: 5, name: '骨科' },
])

// 获取医院名称函数
const getHospitalName = (hospitalId) => {
  const hospital = hospitals.value.find(h => h.id === hospitalId)
  return hospital ? hospital.name : ''
}

// 获取科室名称函数
const getDepartmentName = (departmentId) => {
  const department = departments.value.find(d => d.id === departmentId)
  return department ? department.name : ''
}

// 表单数据
// 修改form响应式对象
const form = reactive({
  name: '',  // 原patientName改为name
  phone: '',
  hospital: '',
  department: '',
  appointmentTime: null,
  duration: 1,
  remarks: '',
  gender: '',  // 新增
  age: null,   // 新增
  caregiverid:'',
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入就诊人姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  hospital: [{ required: true, message: '请选择就诊医院', trigger: 'change' }],
  department: [{ required: true, message: '请选择就诊科室', trigger: 'change' }],
  appointmentTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }]
}

// 计算总价
const totalPrice = computed(() => {
  if (!selectedEscort.value) return 0
  return selectedEscort.value.price * form.duration
})

// 筛选表单数据
const filterForm = reactive({
  money: '',
  gender: '',
  age: '',
  address: '',
  serviceyears: ''
})

// 激活的筛选条件
const activeFilters = computed(() => {
  return Object.fromEntries(
    Object.entries(filterForm).filter(([_, value]) => value !== '')
  );
});

// 筛选条件标签映射
const filterLabels = {
  money: '价格区间',
  gender: '性别',
  age: '年龄区间',
  address: '地区',
  serviceyears: '从业年限'
};

// 移除筛选条件
const removeFilter = (key) => {
  filterForm[key] = '';
  fetchEscortsByFilter();
};

// 根据筛选条件获取陪护师列表
const fetchEscortsByFilter = async () => {
  try {
    const params = Object.fromEntries(
      Object.entries(filterForm).filter(([_, v]) => v !== '')
    );

    const response = await axios.get(`http://${ip}:8000/api/getFilteredCaregivers`, { params });
    escorts.value = response.data.map(e => {
      if (typeof e === 'object' && e !== null) {
        return {
          ...e,
          price: parseFloat(e.money),
          is_available: e.status === 'available'
        };
      }
      return e;
    });
  } catch (error) {
    ElMessage.error('筛选失败');
    console.error('筛选错误:', error.response?.data || error.message);
  }
};

// 根据 ID 获取陪护师信息
const caregiverQueryForm = reactive({
  caregiverid: ''
});

const fetchCaregiverById = async () => {
  if (!caregiverQueryForm.caregiverid) {
    ElMessage.warning('请输入陪诊师ID');
    return;
  }

  try {
    const response = await axios.get(`http://${ip}:8000/api/getCaregiverById`, {
      params: { caregiverid: caregiverQueryForm.caregiverid }
    });

    escorts.value = response.data.map(e => {
      if (typeof e === 'object' && e !== null) {
        return {
          ...e,
          price: parseFloat(e.money),
          is_available: e.status === 'available'
        };
      }
      return e;
    });
  } catch (error) {
    ElMessage.error('查询失败');
    console.error('ID查询错误:', error.response?.data || error.message);
  }
};

// 获取所有陪护师信息
const fetchAllEscorts = async () => {
    const response = await axios.get(`http://${ip}:8000/api/getAllCaregivers`);
    escorts.value = response.data.map(e => {
      if (typeof e === 'object' && e !== null) {
        return {
          ...e,
          price: parseFloat(e.money),
          is_available: e.status === 'available'
        };
      }
      return e;
    });
};

// 获取所有陪护师信息（修复 fetchEscorts 未定义问题）
const fetchEscorts = async () => {
  await fetchAllEscorts();
}

// 计算总价（修复 calculateTotal 未定义问题）
const calculateTotal = () => {
  if (selectedEscort.value) {
    return selectedEscort.value.price * form.duration
  }
  return 0
}

const selectEscort = (escort) => {
  console.log('陪护师数据结构:', escort); // 添加调试信息
  selectedEscort.value = { ...escort };
  console.log('当前选中陪护师:', selectedEscort.value);
  console.log('当前选中陪护师 ID:', selectedEscort.value?.caregiverid);
}

// 下一步
const nextStep = async () => {
  if (activeStep.value === 0) {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        activeStep.value++
      }
    })
    return
  }
  activeStep.value++
}

// 上一步
const prevStep = () => {
  activeStep.value--
}

// 是否显示二维码
const showQRCode = ref(false)
// 二维码链接
const qrCodeUrl = ref('')

// 监听支付方式变化
watch(paymentMethod, async (newMethod) => {
  if (!selectedEscort.value || !form.name) {
    return
  }
  try {
    const { qr_code } = await getPaymentQRCode({
      amount: totalPrice.value,
      payment_method: newMethod
    })
    qrCodeUrl.value = qr_code
    showQRCode.value = true
  } catch (error) {
    ElMessage.error('获取支付二维码失败')
  }
})


// 发布到接单大厅
const publishToHall = () => {
  selectedEscort.value = null
  nextStep()
}

// 路由实例
const router = useRouter();

// 新增日期拆分函数（直接写在组件中）函数中缩短时间格式为 HH:mm（移除秒）
const splitDateTime = (datetime) => {
  const date = new Date(datetime);
  const pad = (num) => num.toString().padStart(2, '0');
  return {
    starttime: `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`,
    time: `${pad(date.getHours())}:${pad(date.getMinutes())}` // 移除秒数
  };
};


const submitOrder = async () => {
  try {
    const timeData = splitDateTime(form.appointmentTime);

    console.log('selectedEscort:', selectedEscort.value);
    console.log('selectedEscort ID:', selectedEscort.value?.caregiverid);
    const patientData = {
      name: form.name,
      phone: form.phone,
      hospital: getHospitalName(form.hospital),
      department: getDepartmentName(form.department),
      starttime: `${timeData.starttime} ${timeData.time}`,
      time: form.duration * 3600,
      gender: form.gender,
      age: form.age,
      caregiverid: selectedEscort.value ? selectedEscort.value.caregiverid : null
    };

    console.log('提交就诊人数据:', patientData);

    // 调用新增就诊人接口
    await axios.post(`http://${ip}:8000/addPatient`, patientData);

    ElMessage.success('就诊人信息已成功保存');

    if (!selectedEscort.value) {
      ElMessage.success('已成功发布到接单大厅');
      router.push('/');
      return;
    }

    // 直接显示支付成功提示
    ElMessage.success('支付成功！');

    // 延迟 1 秒后跳转到首页
    setTimeout(() => {
      router.push('/');
    }, 1000);
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败：' + error.response?.data?.error || error.message);
  }
};


// 预约记录对话框显示状态
const showHistoryDialog = ref(false)
// 预约记录列表
const appointmentHistory = ref([])

// 显示预约记录
const showHistory = async () => {
  try {
    const data = await getAppointmentList()
    appointmentHistory.value = data
    showHistoryDialog.value = true
  } catch (error) {
    ElMessage.error('获取预约记录失败')
  }
}

// 获取订单状态标签类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待支付',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 订单信息
const orderInfo = computed(() => ({
  escort: selectedEscort.value?.name || '',
  name: form.name || '',
  phone: form.phone || '',
  hospital: getHospitalName(form.hospital) || '',
  department: getDepartmentName(form.department) || '',
  appointmentTime: form.appointmentTime ? formatDateTime(form.appointmentTime) : '',
  duration: form.duration ? `${form.duration}小时` : '',
  totalPrice: totalPrice.value ? `¥${totalPrice.value}` : '¥0'
}))

// 组件挂载时获取陪护师信息
onMounted(() => {
  fetchEscorts()
})
</script>

<style scoped lang="scss">
.appointments {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .appointment-steps {
    margin: 20px 0 40px;
  }

  .escort-card {
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;

    &.selected {
      border-color: #409EFF;
      box-shadow: 0 0 8px rgba(64,158,255,.2);
    }
    &:hover {
    transform: translateY(-2px);} // 悬浮效果

    .escort-avatar {
      position: relative;
      text-align: center;
      margin: 20px 0;

      .escort-status {
        position: absolute;
        right: 20px;
        top: 0;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        background: #f56c6c;
        color: #fff;

        &.available {
          background: #67c23a;
        }
      }
    }

    .escort-info {
      padding: 0 20px 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        text-align: center;
      }

      .escort-title {
        text-align: center;
        color: #606266;
        margin: 10px 0;
      }

      .escort-intro {
        color: #606266;
        margin: 10px 0;
        height: 40px;
        overflow: hidden;
      }

      .escort-rating {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px 0;

        .rating-text {
          margin-left: 10px;
          color: #f7ba2a;
        }
      }

      .escort-price {
        text-align: center;
        color: #606266;

        .price {
          font-size: 20px;
          color: #f56c6c;
          font-weight: bold;
        }
      }
    }
  }

  .order-summary {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 20px;
    }

    .order-info-table {
      margin-bottom: 20px;
    }
  }

  .payment-section {
    h3 {
      margin-bottom: 20px;
    }

    .payment-methods {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;

      .el-radio-button {
        flex: 1;

        :deep(.el-radio-button__inner) {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 12px 20px;

          .el-icon {
            margin-right: 8px;
            font-size: 20px;
          }
        }
      }
    }

    .qr-code {
      text-align: center;
      margin-top: 30px;
      padding: 20px;
      border: 1px solid #EBEEF5;
      border-radius: 4px;
      background-color: #FFFFFF;

      img {
        width: 200px;
        height: 200px;
        margin-bottom: 15px;
        object-fit: contain;
      }

      p {
        color: #606266;
        margin: 0;
      }
    }
  }

  .step-actions {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }

  //筛选陪诊师
  .filter-tags {
    margin: 10px 0;
    .el-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }

  .publish-to-hall {
    margin-top: 30px;
    text-align: center;

    .publish-card {
      cursor: pointer;
      transition: all 0.3s;
      max-width: 300px;
      margin: 0 auto;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .publish-content {
        padding: 20px;
        text-align: center;

        h3 {
          margin: 10px 0 5px;
          color: #409EFF;
        }

        p {
          color: #606266;
          margin: 0;
        }
      }
    }
  }
}
</style>